package com.wanyangproject.service;


import android.content.Context;
import android.content.Intent;

import com.wanyangproject.base.BaseService;
import com.wanyangproject.net.util.Constant;
import com.wanyangproject.utils.FileUtil;
import com.wanyangproject.widget.uutils.crypto.MD5Utils;
import com.wanyangproject.widget.uutils.net.DownloadError;
import com.wanyangproject.widget.uutils.net.DownloadListener;
import com.wanyangproject.widget.uutils.net.DownloadManager;

public class OfficeFileService extends BaseService {

    public static void startService(Context context, String enclosureUrl) {
        Intent intent = new Intent(context, OfficeFileService.class);
        intent.setAction(Constant.ACTION_DOWNLOAD);
        intent.putExtra(Constant.ENCLOSURE_URL, enclosureUrl);
        context.startService(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && intent.getAction().equals(Constant.ACTION_DOWNLOAD)) {
            String url = intent.getStringExtra(Constant.ENCLOSURE_URL);
            String filePath = Constant.BASE_PATH + FileUtil.convertFileName(url);
            String fileMD5 = MD5Utils.getFileMD5(url);
            setUrl(url, filePath, fileMD5);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void setUrl(String url, String filePath, String fileMD5) {
        DownloadManager.getInstance().download(url, filePath, fileMD5, new DownloadListener() {
            @Override
            public void onStart(String url, String path) {
                Intent intent = new Intent();
                intent.setAction(Constant.ACTION_DOWNLOAD_INIT);
                mLBMgr.sendBroadcast(intent);
            }

            @Override
            public void onProgress(String url, String path, float p) {
                Intent intent = new Intent();
                intent.setAction(Constant.ACTION_DOWNLOAD_LOADING);
                intent.putExtra(Constant.EXTRA_SIZE, (int) (p * 100));
                mLBMgr.sendBroadcast(intent);
            }

            @Override
            public void onFinish(String url, String path, DownloadError err) {
                Intent intent = new Intent();
                intent.setAction(Constant.ACTION_DOWNLOAD_END);
                intent.putExtra(Constant.ENCLOSURE_PATH, path);
                mLBMgr.sendBroadcast(intent);
                stopSelf();
            }
        });
    }
}